import Vue from 'vue';
import App from './App.vue';
import router from './router';
import ElementUI from 'element-ui';
import VueI18n from 'vue-i18n';
import Contextmenu from "vue-contextmenujs";
import {
    messages
} from './components/common/i18n';
import 'element-ui/lib/theme-chalk/index.css'; // 默认主题
// import './assets/css/theme-green/index.css'; // 浅绿色主题
import './components/common/directives';
import './assets/css/element.css';
// import 'babel-polyfill';
import 'xe-utils';
import 'vxe-table/lib/index.css';
import VXETable from 'vxe-table';
import tool from '@/utils/tool';
import bus from '@/components/common/bus';
import rmcompents from '@/components/rmcompents';
import ddldata from './components/common/ddldata';
import ca from './components/common/ca';
import pinyin from 'pinyin';
import pub from './components/common/public';
import table from './components/common/table.js';
import opt from './components/common/options';
import col from './components/common/CommColumn.js';
import Sortable from 'sortablejs';
import echarts from 'echarts';
import rmConfirm from './components/rmcompents/rm_confirm.js';
import rmDialog from './components/rmcompents/rm_dialog.js';
import voca from 'voca';
import moment from 'moment';
import MaskedInput from 'vue-text-mask';
import dataV from '@jiaminghi/data-view';


Vue.prototype.$rmConfirm = rmConfirm;
Vue.prototype.$rmDialog = rmDialog;

import rm_Login from './components/rmcompents/rm_Login_Comm.js'
Vue.prototype.$rm_Login = rm_Login;

import rm_RptunitStyle from './components/rmcompents/rm_RptunitStyle.js'
Vue.prototype.$rm_RptunitStyle = rm_RptunitStyle;

import rm_uploadFiles from './components/rmcompents/uploadFiles.js'
Vue.prototype.$rm_uploadFiles = rm_uploadFiles;

import rmFieldSort from './components/rmcompents/rm-fieldsort.js'
Vue.prototype.$rmsort = rmFieldSort;

Vue.config.productionTip = false;
Vue.use(VueI18n);
Vue.use(VXETable);
Vue.use(rmcompents);
Vue.use(ElementUI, {
    size: 'small',
});
Vue.use(Contextmenu);
Vue.component('masked-input', MaskedInput);
Vue.use(dataV);



// 按需引入vue-awesome图标
import Icon from 'vue-awesome/components/Icon';
import 'vue-awesome/icons/chart-bar.js';
import 'vue-awesome/icons/chart-area.js';
import 'vue-awesome/icons/chart-pie.js';
import 'vue-awesome/icons/chart-line.js';
import 'vue-awesome/icons/align-left.js';

// 适配flex
import '@/components/common/flexible.js';

// 全局注册图标
Vue.component('icon', Icon);


VXETable.interceptor.add('event.clear_actived', (params, event) => {
    console.log('vxe.....', event.target);
    // return false;
    // 比如点击了某个组件的弹出层面板之后，此时被激活单元格不应该被自动关闭，通过返回 false 可以阻止默认的行为。
    try {
        if (event.target.className.indexOf("vxe-cell") >= 0 ||
            event.target.className.indexOf("el-input__inner") >= 0) {
            return true;
        }


        if (params.cell.children[0].children[0].className.indexOf('el-select') > -1) {
            let tgobj = null;
            if (voca.upperCase(event.target.tagName) == "LI") {
                tgobj = event.target.__vue__;
            } else if (voca.upperCase(event.target.parentNode.tagName) == "LI") {
                tgobj = event.target.parentNode.__vue__;
            }
            if (!tgobj) {
                return true;
            }
            let pselectname1 = params.cell.children[0].children[0].__vue__.$vnode.tag;
            let pselectname2 = tgobj.$parent.$parent.$parent.$vnode.tag;
            if (pselectname1 == pselectname2) {
                return false;
            } else {
                return true;
            }

        }
    } catch (e) {}
})

import ('echarts').then((echarts) => {
    Vue.prototype.$echarts = echarts;
});
Vue.prototype.$tool = tool;
Vue.prototype.$bus = bus;
Vue.prototype.$ddldata = ddldata;
Vue.prototype.$ca = ca;
Vue.prototype.$pinyin = pinyin;
Vue.prototype.$pub = pub;
Vue.prototype.$table = table;
Vue.prototype.$opt = opt;
// Vue.prototype.$col = col;
Vue.prototype.$sortable = Sortable;
Vue.prototype.$v = voca;
Vue.prototype.$moment = moment;

const i18n = new VueI18n({
    locale: 'zh',
    messages,
});

if (Vue.prototype.$tool.getLocalConfig("lng")) {
    i18n.locale = Vue.prototype.$tool.getLocalConfig("lng");
    // console.log('lng load', i18n.locale);
}

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    let isbis = window.location.pathname.indexOf('/bis') >= 0 ? '1' : '0';
    //LIS310
    if (to.fullPath.indexOf('Yz1MSVMzMTA') > -1) {
        console.log(to);
        // base64加密不满4的倍数位会补等于号，因为会参数化为%3D，所以这里要给他去掉，不然会影响解密
        let defaultpath = to.fullPath.replace('=', '').replace('%3D', '');
        let queryparam = window.atob(defaultpath.substring(7));
        let queryarr = queryparam.split('&');
        to.query.c = queryarr[0].substring(2, 8);
        to.query.u = queryarr[1].substring(2);
        to.query.p1 = queryarr[2].substring(3);
    }
    // console.log(isbis);
    if (!!to.query.c) {
        let userno = to.query.u;
        let param = {};
        param.c = to.query.c; //1: 自助报告打印 0：表示仅登录
        param.u = to.query.u; //第三方传入用户s
        param.s = to.query.s; //用作控制全屏 1 全屏
        param.hsp = to.query.hsp; //区域模式 传入院区
        param.p1 = to.query.p1;
        param.p2 = to.query.p2;
        param.p3 = to.query.p3;
        param.p4 = to.query.p4;
        param.p5 = to.query.p5;
        param.p6 = to.query.p6;
        param.p7 = to.query.p7;
        param.p8 = to.query.p8;
        param.p9 = to.query.p9;
        let _nosetwebinfo = to.query.nosetwebinfo;
        //表示外部调用
        let _to = to;
        let _from = from;
        let _next = next;
        Vue.prototype.$tool.removeLocalConfig("bigmodellist");
        Vue.prototype.$tool.request({
                url: "/ucent/login",
                method: "post",
                data: {
                    action: "prelogin",
                    userno: userno,
                    callmode: to.query.c,
                    callparam: param,
                    isbis: isbis, //是否为输血系统
                }
            })
            .then(async res => {
                console.log('1111');
                if (res.lis310multiple) {
                    Vue.prototype.$tool.setLocalConfig("lis310multiple", res.lis310multiple);
                }
                if (res.flag == 1) {
                    userno = res.userno;
                    Vue.prototype.$tool.setSession(Vue.prototype.$tool.loginusername, res.username);
                    Vue.prototype.$tool.setSession(Vue.prototype.$tool.loginuserno, userno);
                    Vue.prototype.$tool.setSession(Vue.prototype.$tool.logintoken, res.msg);
                    Vue.prototype.$tool.setSession(Vue.prototype.$tool.loginutype, res.utype);
                    Vue.prototype.$tool.setSession(Vue.prototype.$tool.otherparam, JSON.stringify(param));
                    Vue.prototype.$tool.setLocalConfig("webver", res.ver);
                    localStorage.setItem("rm_loguser", userno);
                    Vue.prototype.$tool.setLocalConfig("selectedhis", res.selectedhis);
                    Vue.prototype.$tool.setSession(Vue.prototype.$tool.selectedhis, res.selectedhis);
                    // 耗材采购中心
                    Vue.prototype.$tool.setLocalConfig("selinvorg", res.invorgid);
                    Vue.prototype.$tool.setSession("selinvorg", res.invorgid);
                    // 设备采购中心
                    Vue.prototype.$tool.setLocalConfig("seldevorg", res.devorgid);
                    Vue.prototype.$tool.setSession("seldevorg", res.devorgid);
                    //页面登录时获取当前是否为区域LIS模式
                    Vue.prototype.$ddldata.IsAreaModeFun().then(r => {
                        Vue.prototype.$ddldata.IsAreaMode = r;
                    });

                    try {
                        if (typeof jsObj != "undefined") {
                            if (!_nosetwebinfo || _nosetwebinfo != "1") {
                                Vue.prototype.$pub.SetWebInfo(userno, res.selectedhis, isbis);
                            }
                            if (res.ssotoken) {
                                jsObj.SetSSOToken(res.ssotoken);
                            }
                            //设置公司名称
                            if (res.softname || res.compname) {
                                jsObj.SetSoftName(res.softname, res.compname);
                            }
                            if (res.softname) {
                                Vue.prototype.$tool.setLocalConfig("softname", res.softname);
                            } else {
                                Vue.prototype.$tool.removeLocalConfig("softname");
                            }
                            //启动解码
                            jsObj.ReadCard("rmycmd:rundec");
                            if (param.s == "1") {
                                jsObj.SetWindowStyle(false, false, true);
                            } else if (param.s == "2") {
                                jsObj.SetWindowStyle(false, false, false);
                            }
                        }
                    } catch (e) {}
                    if (to.query.c == 1) {
                        Vue.prototype.$pub.innfullscreen = "1";
                    } else if (to.query.c == 'LIS310') {
                        if (res.callmodel) {
                            Vue.prototype.$tool.setLocalConfig('bigmodel', res.callmodel);
                        }
                        var reportidarr = [];
                        if (to.query.p1.indexOf('?') > -1) {
                            reportidarr = to.query.p1
                                .substring(0, to.query.p1.indexOf('?'))
                                .split('-');
                        } else {
                            reportidarr = to.query.p1.split('-');
                        }
                        var rptinfo = {
                            AddBy410: '1',
                            sampledate: reportidarr[0].substring(0, 4) +
                                '-' +
                                reportidarr[0].substring(4, 6) +
                                '-' +
                                reportidarr[0].substring(6),
                            rptunitid: parseInt(reportidarr[1]),
                            sampleno: reportidarr[2].toString(),
                        };
                        Vue.prototype.$tool.setSession('RptTo', JSON.stringify(rptinfo));
                        var prgno = '/' + res.callmenu;
                        // 因为无论多开报告单元是否开启，打开链接都会新开启一个页面，所以不用考虑id
                        next(prgno);
                    }
                    if (res.useca == "1") {
                        try {
                            let cares = await Vue.prototype.$ca.login(res.caparams, res.hiscode2, userno, res.allowbindingcabyself, res.username);
                            if (cares.flag != "1") {
                                Vue.prototype.$alert("CA登陆失败！" + cares.msg, "登陆失败", {
                                    confirmButtonText: "确定",
                                    type: "error",
                                }).then(() => {
                                    tologinform(to, from, next, isbis)
                                });
                            } else {
                                if (res.callmodel) {
                                    console.log('set res.callmodel', res.callmodel);
                                    Vue.prototype.$tool.setLocalConfig("bigmodel", res.callmodel);
                                }
                                next('/' + res.callmenu);
                            }
                        } catch (err) {
                            console.log(err);
                            tologinform(to, from, next, isbis)
                        }
                    } else {
                        next('/' + res.callmenu);
                    }
                } else {
                    await Vue.prototype.$confirm(res.msg, {
                            confirmButtonText: '确定',
                            type: "warning",
                            showCancelButton: false
                        })
                        .then(() => {
                            tologinform(to, from, next, isbis)
                        })
                        .catch(() => {
                            tologinform(to, from, next, isbis)
                        });
                }
            }).catch((ex) => {
                tologinform(to, from, next, isbis)
            });
    } else {
        tologinform(to, from, next, isbis)
    }
    //tologinform(to, from, next)
});

function tologinform(to, from, next, isbis) {
    //console.log(window.location.pathname);
    const role = tool.getSession(tool.loginusername);
    //console.log(to);
    if (isbis == '1') { //2021.2.3 H.S.F. 输血系统登录页面为loginbis
        if (to.path == '/login') {
            next('/loginbis');
        } else if (!role && to.path !== '/loginbis') {
            if (to.path.startsWith('/msgcenter')) {
                next();
            } else if (to.path == '/UserInfoVerify' || to.path == '/UserGetReport') {
                next();
            } else {
                next('/loginbis');
            }
        } else if (to.path == '/dashboard') {
            next('/dashboardbis');
        } else if (to.path == '/datapad') {
            next('/datapad');
        } else if (to.path == '/NBS700') {
            var userno = Vue.prototype.$tool.getSession(Vue.prototype.$tool.loginuserno);
            var url = Vue.prototype.$tool.getSession('weburl');
            var hospcode = Vue.prototype.$tool.getSession('hospcode');
            window.open(url + '/Home/IndexHLYX/user=' + userno + '/model=H/hospital=' + hospcode, '_blank')
        } else if (to.meta.permission) {
            // 如果是管理员权限则可进入，这里只是简单的模拟管理员权限而已
            role === 'admin' ? next() : next('/403');
        } else {
            // 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
            if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
                Vue.prototype.$alert(
                    'vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看',
                    '浏览器不兼容通知', {
                        confirmButtonText: '确定',
                    }
                );
            } else {
                next();
            }
        }
    } else {
        if (!role && to.path !== '/login') {
            console.log('to.path', to.path);
            if (to.path.startsWith('/msgcenter')) {
                next();
            } else if (to.path == '/UserInfoVerify' || to.path == '/UserGetReport') {
                next();
            } else {
                next('/login');
            }
        } else if (to.meta.permission) {
            // 如果是管理员权限则可进入，这里只是简单的模拟管理员权限而已
            role === 'admin' ? next() : next('/403');
        } else {
            // 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
            if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
                Vue.prototype.$alert(
                    'vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看',
                    '浏览器不兼容通知', {
                        confirmButtonText: '确定',
                    }
                );
            } else {
                next();
            }
        }
    }

}

router.afterEach((to, from, next) => {
    bus.$emit("clearstatumsg", 3);
    bus.$emit("clearstatumsg", 4);
    document.onkeydown = null;
    document.onkeyup = null;
    document.onkeypress = null;
    //console.log('afterEach');
    setTimeout(() => {
        if (window.gc) {
            window.gc();
        }
    }, 10);


    if (to.path.indexOf("datapad") > 0) {
        bus.$emit('routerchanged', from);
    } else {
        if (to.matched[1] && to.path != '/' + to.matched[1].components.default.name) {
            if (to.path != '/404' && to.path != "/NBS831") {
                Vue.prototype.$alert(to.path + ' 页的name设置不一致，请检查，当前name： ' + to.matched[1].components.default.name, {
                    confirmButtonText: '确定',
                });
            }
        }
    }
    bus.$emit('routerchanged', from);
});

new Vue({
    router,
    i18n,
    render: h => h(App),
}).$mount('#app');
